/**
 * Created with CLion.
 * Description: 
 * User: loong
 * Date: 2024/6/27
 * Time: 17:00
 */

#ifndef OVERLAPLAYOUT_H
#define OVERLAPLAYOUT_H
#include <QLayout>
#include <memory>
namespace Upgrade {
    class OverlapLayout : public QLayout
    {
    public:
        explicit OverlapLayout(QWidget *parent = nullptr, int spacing = 50, const QString &_order_property = "OrderProperty");

        ~OverlapLayout() override;

        void Resort();

        void         addItem(QLayoutItem *item) override;
        QSize        sizeHint() const override;
        QSize        minimumSize() const override;
        int          count() const override;
        QLayoutItem *itemAt(int index) const override;
        QLayoutItem *takeAt(int index) override;
        void         setGeometry(const QRect &rect) override;

        // 如果_func为空，则按照T的 > 排序，否则按照_func排序
        template<typename T>
        void SetSortFunction(std::function<bool (const T &,const T &)> _func = nullptr)
        {
            sortFunction = [=](QLayoutItem *a, QLayoutItem *b) -> bool {
                T valueA = a->widget()->property(order_property_name_.toLocal8Bit()).template value<T>();
                T valueB = b->widget()->property(order_property_name_.toLocal8Bit()).template value<T>();

                return nullptr == _func ? valueA > valueB : _func(valueA,valueB);
            };
        }

        QString GetSortPropertyName() { return order_property_name_; };

        void    SetSortPropertyName(const QString &_name) { order_property_name_ = _name; };
    private:
        void doLayout(const QRect &rect);

    private:
        QList<QLayoutItem *>                              itemList;
        int                                               overlapSpacing;// 重叠间距
        QString                                           order_property_name_;
        std::function<bool(QLayoutItem *, QLayoutItem *)> sortFunction {nullptr};
    };

}// namespace Upgrade

#endif//OVERLAPLAYOUT_H
